package com.utaedang.jesseclub;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;

import net.daum.mobilead.impl.animation.AnimationType;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.Ad;
//import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;

import com.cauly.android.ad.AdInfo;
import com.cauly.android.ad.AdListener;
//import com.cauly.android.ad.AdView;

import com.utaedang.jesseclub.utils.Function.AlarmWakeLock;
import com.utaedang.jesseclub.utils.DateUtil;
import com.utaedang.jesseclub.utils.GlobalContext;
import com.utaedang.jesseclub.utils.JesseclubBoardHTMLParse;

public class JesseclubActivity extends Activity implements AdListener{
	
	private static final String TAG = JesseclubActivity.class.getSimpleName();
	private com.google.ads.AdView aAdView;
	private com.cauly.android.ad.AdView cAdView;
	private com.cauly.android.ad.AdInfo cAdInfo;
	private net.daum.mobilead.MobileAdView dAdView;
	private boolean isInterstitial;
    private Display display;
    
	private ArrayList<HashMap<String, String>> data;
	private SimpleAdapter sa;
	private JesseclubBoardHTMLParse hp;
	private Activity activity;
	private boolean mFlag = false;
	private FrameLayout flayout;
	private LinearLayout glayout;
	
	private Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if(msg.what == 0){
				mFlag = false;
				Log.d("", "handleMessage mFloag : " + mFlag);
			}
		}
	};

	private final Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			listUpdate();
		}
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //Title 변경 방법 1 순서 지킬 것
        Window window = getWindow();
        window.requestFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.jesseboard);
        window.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
        
        activity = this;
        
        //Title 변경 방법 2
        //activity.setTitle(getResources().getString(R.string.app_title));
        
        LinearLayout layout = (LinearLayout)findViewById(R.id.layout); //제일 바깥 LinearLayout, xml에서 weight="1" 줄것!
        flayout = new FrameLayout(this); //중간의 FrameLayout
        GradientDrawable gradient = new GradientDrawable(GradientDrawable.Orientation.
        		BOTTOM_TOP, new int[]{Color.BLACK, 0xff424242}); //그라데이션 생성
        flayout.setBackgroundDrawable(gradient); 
        glayout = new LinearLayout(this); //제일 안쪽 Gravity용 LinearLayout
        glayout.setGravity(0x11);
        glayout.setPadding(0, 3, 0, 3);
        ProgressBar progress = new ProgressBar(this); // ProgressBar 생성
        progress.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
        // ProgressBar의 width, height를 레이아웃에 맞춤. 이 과정이 있어야 틀에 맞게 이쁘게 나옴..
        
        ListView list = new ListView(this);

        TextView txtView = new TextView(this);
        txtView.setText("게시물 목록");
        txtView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
        txtView.setHeight(40);
        txtView.setTextSize(20);
        txtView.setGravity(Gravity.CENTER_VERTICAL);
        glayout.addView(progress);
        flayout.addView(glayout);
        
        /*
		 * 광고 설정 부분 시작
		 * 카울리 -> 아담 -> 애드몹 순서
		 */
		//1.애드몹
		//AdmobCpcAd();

		//2.카울리
		//전면 광고 사용 시
	    /*
	    display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        
		int height = display.getHeight();
		int width = display.getWidth();
		int layout_height = 0;
		if (height > width) {
			layout_height = height / 10;
		} else {
			layout_height = width / 10;
		}
  		CaulyInterstitialAd();
  		*/
		//CPC 광고 사용 시
		CaulyCpcAd();
		
		//3.아담
		//AdamCpcAd();
        
        layout.addView(flayout);
        layout.addView(txtView);
        layout.addView(list);
        
        display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        
		int height = display.getHeight();
		int width = display.getWidth();
		int layout_height = 0;
		if (height > width) {
			layout_height = height / 10;
		} else {
			layout_height = width / 10;
		}
		
		//전면 광고 사용 시
		//CaulyInterstitialAd();
		
		/*카울리
		//데이터 채우기
	    AdInfo info = new AdInfo();
	    info.initData("CAULY", "cpm", "all", "all", "off", "left_slide", "yes", 30, true);
	        
	    //광고 View
	    AdView adView2 = new AdView(this);
	        
	    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
	 	LayoutParams.FILL_PARENT,
	 	LayoutParams.WRAP_CONTENT); 
	    
	    //부모 레이어 하단에 위치할때.
	    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
	    adView2.setVisibility(View.VISIBLE);
	    adView2.setLayoutParams(params);
	    adView2.setAdListener(this);

	    //레이아웃 적용.
	    layout.addView(adView2);
	    */
		
        /*
		adView = new AdView(this, AdSize.BANNER, PUBLISHER_ID);
		LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
		layout.addView(adView);
		layout.setHorizontalGravity(android.view.Gravity.CENTER_HORIZONTAL);
		adView.setAdListener(this);
		AdRequest request = new AdRequest();
		adView.loadAd(request);
*/
		/* 테스트 용
		 * 시작
		 * 
		 * //먼저 테스트용 에뮬레이터에서 요청하겠다고 adRequest를 생성해놓습니다. 
		 * AdRequest adRequest = new AdRequest(); 
		 * adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
		 * adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID); LinearLayout
		 * layout = (LinearLayout)findViewById(R.id.mainLayout);
		 * 
		 * layout.addView(adView); //아까 생성한 adRequest를 요청합니다.
		 * adView.loadAd(adRequest);
		 * 
		 * 끝
		 */
        
        data = new ArrayList<HashMap<String, String>>();
        
        //list = (ListView)findViewById(R.id.listView);
     		
        hp = new JesseclubBoardHTMLParse(activity, handler, data);
        
        sa = new SimpleAdapter(activity, data, R.layout.jsc_list_row,
        		new String[]{"title","writer","date","url"}, new int[]{R.id.tv_title, R.id.tv_writer, R.id.tv_date, R.id.tv_url});
        
        list.setAdapter(sa);
        
        hp.open();
        
		list.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.jsc_list_row, null);
				HashMap<String, String> itemData = (HashMap<String, String>) sa.getItem(position);
				
				//Toast.makeText(getApplicationContext(), itemData.get("title").toString() + ", " + itemData.get("writer").toString() + ", " + itemData.get("date").toString(), Toast.LENGTH_SHORT).show();
				
				//추천주일 경우만 monitoring 들어감
				if(itemData.get("title").toString().indexOf("추천주")>0){
					Intent intent = new Intent(getApplicationContext(), JesseclubDetailActivity.class);
				    intent.putExtra("url", itemData.get("url").toString());
				    startActivity(intent);
				}else{
					Toast.makeText(getApplicationContext(), "결과 요약 입니다.", Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		//항상 켜짐 유지
        if(Prefs.getDisplayOff(this)){
        	Log.d(TAG, "Screen On");
        	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        	AlarmWakeLock.wakeLock(getBaseContext());
        }else{
        	Log.d(TAG, "Screen Off");
        	getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        	AlarmWakeLock.releaseWakeLock();
        }

    }
    
	// 애드몹
	private void AdmobCpcAd() {
		aAdView = new com.google.ads.AdView(this, com.google.ads.AdSize.BANNER,
				GlobalContext.ADMOB_ID); // 애드몹 생성
		aAdView.setAdListener((com.google.ads.AdListener) this);
		aAdView.setBackgroundColor(Color.BLACK);
		com.google.ads.AdRequest request = new com.google.ads.AdRequest();
		aAdView.loadAd(request);

		flayout.addView(aAdView);
	}

	// 카울리 전면광고
	private void CaulyInterstitialAd() {
		// 광고 정보 셋팅
		cAdInfo = new com.cauly.android.ad.AdInfo();
		cAdInfo.setPriority(Thread.NORM_PRIORITY); // Thread 우선 순위 (1 ~ 10)
		cAdInfo.initData(GlobalContext.CAURY_ID, "cpm", "all", "all", "off",
				"default", "yes", 0, false);

		// 광고 View
		cAdView = new com.cauly.android.ad.AdView(this);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		cAdView.setVisibility(View.VISIBLE);
		cAdView.setAdListener((com.cauly.android.ad.AdListener) this);
		cAdView.setLayoutParams(params);
		// 부모 레이아웃.
		flayout.addView(cAdView);

		isInterstitial = true;
	}

	// 카울리 CPC광고
	private void CaulyCpcAd() {
		// 광고 정보 셋팅
		cAdInfo = new com.cauly.android.ad.AdInfo();
		cAdInfo.setPriority(Thread.NORM_PRIORITY); // Thread 우선 순위 (1 ~ 10)
		cAdInfo.initData(GlobalContext.CAURY_ID, "cpc", "all", "all", "off",
				"left_slide", "yes", 30, true);

		// 광고 View
		cAdView = new com.cauly.android.ad.AdView(this);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		// 부모 레이어 하단에 위치할때.
		// params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		// 부모 레이어 상단에 위치할때.
		params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		cAdView.setVisibility(View.VISIBLE);
		cAdView.setAdListener((com.cauly.android.ad.AdListener) this);
		cAdView.setLayoutParams(params);

		flayout.addView(cAdView);

		isInterstitial = false;
	}

	// 아담 CPC
	private void AdamCpcAd() {
		// 할당 받은 clientId 설정
		net.daum.mobilead.AdConfig.setClientId(GlobalContext.ADAM_ID);

		// Ad@m 광고 뷰 생성 및 설정
		dAdView = new net.daum.mobilead.MobileAdView(this);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		// 부모 레이어 하단에 위치할때.
		// params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		// 부모 레이어 상단에 위치할때.
		params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		// Animation 효과 : 기본 값은 AnimationType.NONE
		dAdView.setAnimationType(AnimationType.FLIP_VERTICAL);

		dAdView.setAdListener((net.daum.mobilead.AdHttpListener) this);
		dAdView.setVisibility(View.VISIBLE);

		flayout.addView(dAdView, params);

	}
    
    // ListView 갱신
    private void listUpdate()
    {
    	sa.notifyDataSetChanged();
    }

    
    @Override
    public void onBackPressed() {
    	if(!mFlag){
    		Toast.makeText(activity, "'뒤로' 버튼을 한번 더 누르시면 종료됩니다.", Toast.LENGTH_SHORT).show();
    		mFlag = true;
    		mHandler.sendEmptyMessageDelayed(0, 1000*2);
    	}else{
    		moveTaskToBack(true);
    		finish();
    	}
    }

    @Override
	public void onNewIntent(final Intent newIntent) {
		super.onNewIntent(newIntent);

		boolean kill_app = newIntent.getBooleanExtra("KILL_APP", false);
		if (kill_app == true) {
			finish();
			requestKillProcess(this);
		}
	}

	public void requestKillProcess(final Context context) {

		int sdkVersion = Integer.parseInt(Build.VERSION.SDK);

		if (sdkVersion < 8) {
			ActivityManager am = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			am.restartPackage(getPackageName());
		} else {
			new Thread(new Runnable() {
				public void run() {
					ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
					String name = getApplicationInfo().processName;

					while (true) {
						List<RunningAppProcessInfo> list = am
								.getRunningAppProcesses();

						for (RunningAppProcessInfo i : list) {
							if (i.processName.equals(name) == true) {

								if (i.importance >= RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
									am.restartPackage(getPackageName());

								Thread.yield();
								break;
							}
						}
					}
				}

			}, "Process Killer").start();
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(aAdView != null)
			aAdView.destroy();
		if(dAdView != null)
			dAdView.destroy();
		cAdView.setVisibility(View.GONE);
		cAdView = null;
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		AlarmWakeLock.releaseWakeLock();
	}
	
	@Override
	protected void onPause() {
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    	AlarmWakeLock.releaseWakeLock();
    	super.onPause();
	}


	// 현재 액티비티로 돌아오면 실행
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//항상 켜짐 유지
        if(Prefs.getDisplayOff(this)){
        	Log.d(TAG, "Screen On");
        	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        	AlarmWakeLock.wakeLock(getBaseContext());
        }else{
        	Log.d(TAG, "Screen Off");
        	getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        	AlarmWakeLock.releaseWakeLock();
        }
	}

	// AdMob : implements AdMob Event Listeners [START]
    /*
	public void onDismissScreen(Ad arg0) {
		Log.d(TAG, "onDismissScreen");
	}

	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
		Log.d(TAG, "failed to receive ad (" + arg1 + ")");
	}

	public void onLeaveApplication(Ad arg0) {
		Log.d(TAG, "onLeaveApplication");
	}

	public void onPresentScreen(Ad arg0) {
		Log.d(TAG, "onPresentScreen");
	}

	public void onReceiveAd(Ad arg0) {
		Log.d(TAG, "onReceiveAd");
	}
	*/
	
	// AdMob : implements AdMob Event Handlers [END]

	// Cauly : implements Cauly Event Listeners [START]
	public void onCloseInterstitialAd() {
		// TODO Auto-generated method stub
		CaulyCpcAd();		
	}

	public void onFailedToReceiveAd(boolean arg0) {
		Log.d("onFailedToReceiveAd", ""+cAdView.getErrorCode());
		Log.d("onFailedToReceiveAd", ""+cAdView.getErrorMessage());
		
		/*
		 * 전면광고가 없거나 최소 요청 시간 미만시 cpc광고를 호출 
		 */
		if(cAdView.getErrorCode() == GlobalContext.CAULY_INTERSTITIAL_NO_FILLED_AD 
				|| cAdView.getErrorCode() == GlobalContext.CAULY_INTERSTITIAL_NOT_PERMITED) {
			Log.e("onFailedToReceiveAd", "전면광고 없음");
			CaulyCpcAd();
		} else {
			//타사 광고를 호출하거나 개발사 내부 광고를 호출
			flayout.removeAllViews();
			AdamCpcAd();
		}
		
	}

	public void onReceiveAd() {
		Log.d("onReceiveAd", ""+cAdView.getErrorCode());

		if(cAdView.getErrorCode() == GlobalContext.CAULY_INVALID_APPCODE) {
			// 앱코드가 부정확하므로 확인이 필요합니다. 
			Log.e("onReceiveAd", "앱코드가 부정확하므로 확인이 필요합니다.");
		}
		
		if(!isInterstitial)
		{
			flayout.removeAllViews();
			//if(!cAdView.isChargeableAd()) {
				// 타사 광고를 호출하거나 개발사 내부 광고를 호출
				//flayout.addView(glayout);
				//flayout.addView(adView);
			//} else {
				flayout.addView(glayout);
				flayout.addView(cAdView);
			//}
		}
	}
	// Cauly : implements Cauly Event Listeners [END]
	
	// ad@m : implements Cauly Event Listeners [START]
	public void didDownloadAd_AdListener() {
		flayout.removeAllViews();
		AdamCpcAd();
	}

	public void failedDownloadAd_AdListener(int arg0, String arg1) {
		flayout.removeAllViews();
		AdmobCpcAd();	
	}
	// ad@m : implements Cauly Event Listeners [END]

}